import './table2.less'

import React, { useContext, useEffect, useRef, useState } from 'react';
import type { InputRef, DatePickerProps } from 'antd';
import { Button, DatePicker, Form, Input, Popconfirm, Table, Select, InputNumber } from 'antd';
import type { FormInstance } from 'antd/es/form';
import dayjs from 'dayjs';
import locale from 'antd/es/date-picker/locale/en_US';
const EditableContext = React.createContext<FormInstance<any> | null>(null);

interface Item {
    key: string;
    keyWord: string;
    subject: string;
    auxiliary: string;
    getMoney: number;
    sendMoney: number
}

interface EditableRowProps {
    index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    );
};

interface EditableCellProps {
    title: React.ReactNode;
    editable: boolean;
    children: React.ReactNode;
    dataIndex: keyof Item;
    record: Item;
    handleSave: (record: Item) => void;
}

const EditableCell: React.FC<EditableCellProps> = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
}) => {
    const [editing, setEditing] = useState(false);
    const [editing2, setEditing2] = useState(false);
    const [editing3, setEditing3] = useState(false);
    const [editing4, setEditing4] = useState(false);
    const [editing5, setEditing5] = useState(false);
    const inputRef = useRef<InputRef>(null);
    const numberInputRef = useRef<InputRef>(null);
    const numberInputRef2 = useRef<InputRef>(null);

    const selRef = useRef<InputRef>(null);
    const pickRef = useRef<InputRef>(null);
    const form = useContext(EditableContext)!;
    type PickerType = 'time' | 'date';
    const [type, setType] = useState<PickerType>('time');
    useEffect(() => {
        if (editing) {
            inputRef.current!.focus();
        }
        if (editing4) {
            numberInputRef.current!.focus();
        }
        if (editing5) {
            numberInputRef2.current!.focus();
        }
    }, [editing, editing4, editing5]);

    const toggleEdit = () => {
        console.log(dataIndex)
        if (dataIndex == 'keyWord') {

            setEditing(!editing);
        } else if (dataIndex == 'subject') {
            console.log(dataIndex.valueOf)
            setEditing2(!editing2);
        } else if (dataIndex == 'auxiliary') {
            setEditing3(!editing3);
        }
        else if (dataIndex == 'getMoney') {
            setEditing4(!editing4);
        }
        else if (dataIndex == 'sendMoney') {
            setEditing5(!editing5);
        }
        if (dataIndex == 'keyWord') {
            form.setFieldsValue({ ...record, [dataIndex]: dayjs(record[dataIndex], 'YYYY-MM-DD') });
        } else {
            form.setFieldsValue({ ...record, [dataIndex]: record[dataIndex] });
        }


    };

    const [values1,setValue1]=useState([{}]);
    const save = async () => {
        try {
            const values = await form.validateFields();

            toggleEdit();
            handleSave({ ...record, ...values });
            console.log({...record, ...values});
            values1.push({...record, ...values});
            setValue1(values1)
            console.log('values1',values1);
            
            
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };

    // const changeValue=()=>{
    //     console.log('得到数据',values1);
        
    // }
    // changeValue();
    // const onChange: DatePickerProps['onChange'] = (date, dateString) => {
    //     console.log(date, dateString);
    // };
    let childNode = children;

    if (editable) {
        if (editing) {
            childNode = <Form.Item
                style={{ margin: 0 }}
                name={dataIndex}
            >
                <Input ref={inputRef} onPressEnter={save} onBlur={save} />
                {/* onChange={(e:any)=>{form.setFieldsValue(dataIndex,e)}} */}
            </Form.Item>

        } else if (editing2) {
            childNode = <Form.Item

                style={{ margin: 0 }}
                name={dataIndex}
            >
                <Select onBlur={save}
                    options={[
                        { value: '1001库存现金', label: '1001库存现金' },
                        { value: '1012其他货币资金', label: '1012其他货币资金' },
                        { value: '1101短期投资', label: '1101短期投资' },
                        { value: '1121应收票据', label: '1121应收票据' }
                    ]}
                />
            </Form.Item>
        } else if (editing3) {
            childNode = <Form.Item
                style={{ margin: 0 }}
                name={dataIndex}
            >{'经理、客户'}
            </Form.Item>
        }
        else if (editing4) {
            childNode = <Form.Item
                style={{ margin: 0, width: 200 }}
                name={dataIndex}
            ><Input
                    defaultValue={0.00}
                    onPressEnter={save} onBlur={save}
                    ref={numberInputRef} />
            </Form.Item>
        }
        else if (editing5) {
            childNode = <Form.Item
                style={{ margin: 0, width: 200 }}
                name={dataIndex}
            ><Input
                    defaultValue={0.00}
                    onPressEnter={save} onBlur={save}
                    ref={numberInputRef2} />
            </Form.Item>
        }
        else {
            childNode = <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
                {children}
            </div>
        }
    }

    return <td {...restProps}>{childNode}</td>;
};

type EditableTableProps = Parameters<typeof Table>[0];

interface DataType {
    key: React.Key;
    keyWord: string;
    subject: string;
    auxiliary: string;
    getMoney: number;
    sendMoney: number
}

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

function NewTable() {
    const [dataSource, setDataSource] = useState<DataType[]>([
        {
            key: '0',
            keyWord: 'keyWord',
            subject: 'subject',
            auxiliary: 'auxiliary',
            getMoney: 0,
            sendMoney: 0
        }
    ]);

    const [count, setCount] = useState(2);

    const handleDelete = (key: React.Key) => {
        const newData = dataSource.filter((item) => item.key !== key);
        setDataSource(newData);
    };

    const defaultColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
        {
            title: '摘要',
            dataIndex: 'keyWord',
            width: '15%',
            editable: true,
        },
        {
            title: '科目',
            dataIndex: 'subject',
            width: '15%',
            editable: true,
        },
        {
            title: '辅助',
            dataIndex: 'auxiliary',
            editable: false,
        },

        {
            title: '借方余额',
            dataIndex: 'getMoney',
            editable: true,
        },

        {
            title: '贷方余额',
            dataIndex: 'sendMoney',
            editable: true,
        }
    ];

    const handleAdd = () => {
        const newData: DataType = {
            key: count,
            keyWord: `keyWord`,
            subject: 'subject',
            auxiliary: `auxiliary`,
            getMoney: 0,
            sendMoney: 0
        };
        setDataSource([...dataSource, newData]);
        setCount(count + 1);
    };

    const handleSave = (row: DataType) => {
        const newData = [...dataSource];
        const index = newData.findIndex((item) => row.key === item.key);
        const item = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row,
        });
        setDataSource(newData);
    };

    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };

    const columns = defaultColumns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: DataType) => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                handleSave,
            }),
        };
    });
    return <div className='table2'>
        <Table
            style={{ width: 'calc(100% - 20px)', marginLeft: '10px' }}
            components={components}
            rowClassName={() => 'editable-row'}
            bordered
            dataSource={dataSource}
            columns={columns as ColumnTypes}
            footer={() => <>
                <div className="footer">
                    <div className='footChild'></div>
                    <div className='footChild'></div>
                    <div className='footChild' style={{textAlign:'right'}}>合计：</div>
                    <div className='footChild' >{85.00}</div>
                    <div className='footChild'>{85.00}</div>
                </div></>}
/>
    <div className = "addRow" onClick = { handleAdd } >+</div>
    </div >
}
export default NewTable